<template>
  <div class="tinymce-editor"  @click="imageChange($event)" >
    <editor
      v-if="!reloading"
      v-model="myValue"
      :disabled="disabled"
      :init="init"
      @onClick="onClick">
    </editor>
    <!-- 富文本图片放大 -->
    <div class="tinymce-img-preview" v-show="imgPreview.show" @click="cancelImgPreview">
      <!-- 关闭按钮 -->
      <span class="tinymce-img-preview-content-close" @click="cancelImgPreview">&times;</span>
      <img class="tinymce-img-preview-content" @click.stop="cancelImgPreview" :src="imgPreview.img" alt="" />
    </div>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/media'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/fullscreen'
import 'tinymce/icons/default'
import { uploadAction,getFileAccessHttpUrl } from '@api/manage'
import { getVmParentByName } from '@/utils/util'
export default {
  components: {
    Editor
  },
  props: {
    value: {
      type: String,
      required:false
    },
    triggerChange:{
      type: Boolean,
      default: false,
      required:false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default: 'lists image link media table textcolor wordcount contextmenu fullscreen paste preview'
    },
    toolbar: {
      type: [String, Array],
      default: 'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink image media table | removeformat | preview fullscreen',
      branding:false
    }
  },
  data() {
    return {
      //初始化配置
      init: {
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/lightgray',
        convert_urls: false,
        height: 300,
        plugins: this.plugins,
        toolbar: this.disabled?false:this.toolbar,
        branding: false,
        menubar: false,
        paste_data_images: true,
        inline: this.disabled,
        disabled: this.disabled,
        resize: !this.disabled,
        statusbar: !this.disabled,
        content_style:`*{ padding:0; margin:0; }
          html, body { height:100%; }
          img { max-width:100%; display:block;height:auto; }
          a { text-decoration: none; }
          iframe { width: 100%; }
          table { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
          .mce-object-iframe { width:100%; box-sizing:border-box; margin:0; padding:0; }
          ul,ol { list-style-position:inside; }`,
        toolbar_drawer: false,
        images_upload_handler: (blobInfo, success) => {
          if(this.disabled){
            // 如果是禁用状态 则不进行上传，防止base64的数据每次加载时上传数据
            return
          }
          let formData = new FormData()
          formData.append('file', blobInfo.blob(), blobInfo.filename());
          formData.append('biz', "jeditor");
          formData.append("jeditor","1");
          uploadAction(window._CONFIG['domianURL']+"/file/upload", formData).then((res) => {
            if (res.success) {
              if(res.message == 'local'){
                const img = 'data:image/jpeg;base64,' + blobInfo.base64()
                success(img)
              }else{
                let img = getFileAccessHttpUrl(res.message)
                success(img)
              }
            }
          })
        }
      },
      myValue: this.value,
      reloading: false,
      imgPreview:{
        img:"",
        show:false
      },
    }
  },
  mounted() {
    this.initATabsChangeAutoReload()
  },
  methods: {

    reload() {
      this.reloading = true
      this.$nextTick(() => this.reloading = false)
    },

    onClick(e) {
      this.$emit('onClick', e, tinymce)
    },
    //可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.myValue = ''
    },
    imageChange(e){
      console.log(e.target.nodeName )
      if (e.target.tagName == 'IMG') {
        this.imgPreview.img = e.target.src
        this.imgPreview.show = true
      }
    },
    cancelImgPreview(){
      this.imgPreview.show = false;
    },
    /**
     * 自动判断父级是否是 <a-tabs/> 组件，然后添加事件监听，自动触发reload()
     *
     * 由于 tabs 组件切换会导致 tinymce 无法输入，
     * 只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
     */
    initATabsChangeAutoReload() {
      // 获取父级
      let tabs = getVmParentByName(this, 'ATabs')
      let tabPane = getVmParentByName(this, 'ATabPane')
      if (tabs && tabPane) {
        // 用户自定义的 key
        let currentKey = tabPane.$vnode.key
        // 添加事件监听
        tabs.$on('change', (key) => {
          // 切换到自己时执行reload
          if (currentKey === key) {
            this.reload()
          }
        })
        //update--begin--autor:liusq-----date:20210316------for：富文本编辑器tab父组件可能导致的赋值问题------
        this.reload()
        //update--end--autor:liusq-----date:20210316------for：富文本编辑器tab父组件可能导致的赋值问题------
      }else{
        //update--begin--autor:wangshuai-----date:20200724------for：富文本编辑器切换tab无法修改------
        let tabLayout = getVmParentByName(this, 'TabLayout')
        //update--begin--autor:liusq-----date:20210713------for：处理特殊情况excuteCallback不能使用------
        try {
          tabLayout.excuteCallback(() => {
            this.reload()
          })
        } catch (error) {
          if (tabLayout) {
            this.reload()
          }
        }
        //update--end--autor:liusq-----date:20210713------for：处理特殊情况excuteCallback不能使用------
        //update--begin--autor:wangshuai-----date:20200724------for：文本编辑器切换tab无法修改------
      }
    },

  },
  watch: {
    value(newValue) {
      this.myValue = (newValue == null ? '' : newValue)
    },
    myValue(newValue) {
      if(this.triggerChange){
        this.$emit('change', newValue)
      }else{
        this.$emit('input', newValue)
      }
    }
  }
}

</script>
<style scoped>
.tinymce-editor img{
  max-width: 80%;
  max-height: 90%;
}
.tinymce-img-preview{
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  z-index: 999;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
}
/* 设置弹出图片的样式 */
.tinymce-img-preview-content {
  margin: auto;
  display: block;
}
/* 设置弹出图片的动画，添加动画 */
.tinymce-img-preview-content {
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}
@-webkit-keyframes zoom {
  from {
    -webkit-transform: scale(0)
  }
  to {
    -webkit-transform: scale(1)
  }
}
@keyframes zoom {
  from {
    transform: scale(0)
  }

  to {
    transform: scale(1)
  }
}

  /* 设置span标签的关闭按钮样式 */
.tinymce-img-preview-content-close {
  /* Hidden by default */
  position: fixed;
  /* 设置显示的优先层级级别 */
  z-index: 1000;
  width: 66px;
  height: 66px;
  text-align: center;
  border-radius: 33px;
  top: 55px;
  right: 55px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
  background-color: rgba(0, 0, 0, 0.2);
}
.tinymce-img-preview-content-close:hover,
.tinymce-img-preview-content-close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}
/* 小屏幕中图片宽度为 100% */
@media only screen and (max-width: 700px) {
  .tinymce-img-preview-content {
    width: 100%;
  }
}
</style>